package study.eggs.validation.validator;

import com.google.common.primitives.Longs;
import lombok.extern.slf4j.Slf4j;
import study.eggs.exception.param.EmptyValueException;
import study.eggs.exception.param.ValueIllegalException;
import study.eggs.validation.constraints.Number;

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 枚举验证器
 */
@Slf4j
public class NumberValidator implements Validator {

    private static final List<Class> SUPPORT_LT = Arrays.asList(String.class);

    @Override
    public boolean support(Class<?> clazz) {
        boolean flag = SUPPORT_LT.stream()
                .anyMatch(e -> e == clazz);
        return flag;
    }

    @Override
    public void validate(String name, Object value, Annotation annot) {
        Number number = (Number) annot;
        //非空
        if (number.required() && Objects.isNull(value)) {
            throw new EmptyValueException(name);
        }
        //枚举
        if (!Objects.isNull(value)) {
            String[] enums = number.enums();
            List<Long> lt = Arrays.asList(enums).stream()
//                    .filter()
                    .map(Longs::tryParse)
                    .collect(Collectors.toList());
            if (!lt.contains(value)) {
                throw new ValueIllegalException(name);
            }
        }
    }
}
